import React, { useState, useEffect } from 'react'
import { View, Text, Button, Switch, Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useAppContext } from '../../store'
import { pointsUtils } from '../../utils/pointsUtils'
import { scheduledTasks } from '../../utils/scheduledTasks'
import { CloudDataManager } from '../../utils/cloud'
import NetworkStatus from '../../components/NetworkStatus'
import './index.scss'

const Settings: React.FC = () => {
  const { state, dispatch } = useAppContext()
  const [isOnline, setIsOnline] = useState(true)
  const [processing, setProcessing] = useState(false)
  const [notificationEnabled, setNotificationEnabled] = useState(true)
  const [birthday, setBirthday] = useState<string>('')
  const [savingBirthday, setSavingBirthday] = useState(false)
  
  // 初始化时加载设置
  useEffect(() => {
    // 加载通知设置
    const notificationSetting = Taro.getStorageSync('notificationEnabled')
    if (notificationSetting !== '') {
      setNotificationEnabled(!!notificationSetting)
    }
    
    // 加载生日设置
    if (state.currentUser?.birthday) {
      const date = new Date(state.currentUser.birthday)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      setBirthday(`${month}-${day}`)
    }
  }, [state.currentUser])
  
  // 处理网络状态变化
  const handleNetworkStatusChange = (online: boolean) => {
    setIsOnline(online)
  }
  
  // 手动触发积分过期检查
  const handleCheckPointsExpiration = async () => {
    if (!state.currentUser || !isOnline) return
    
    setProcessing(true)
    try {
      // 检查用户权限
      if (state.currentUser.role !== 'chef') {
        Taro.showToast({
          title: '权限不足',
          icon: 'none'
        })
        return
      }
      
      // 执行积分过期处理
      const expiredCount = await pointsUtils.processExpiredPoints()
      
      Taro.showToast({
        title: `已处理${expiredCount}个过期积分`,
        icon: 'success'
      })
    } catch (error) {
      console.error('积分过期处理失败:', error)
      Taro.showToast({
        title: '处理失败',
        icon: 'none'
      })
    } finally {
      setProcessing(false)
    }
  }
  
  // 手动触发厨师状态检查
  const handleCheckChefStatus = async () => {
    if (!state.currentUser || !isOnline) return
    
    setProcessing(true)
    try {
      // 检查用户权限
      if (state.currentUser.role !== 'chef') {
        Taro.showToast({
          title: '权限不足',
          icon: 'none'
        })
        return
      }
      
      // 执行厨师状态检查
      await scheduledTasks.checkChefStatus()
      
      Taro.showToast({
        title: '厨师状态已更新',
        icon: 'success'
      })
    } catch (error) {
      console.error('厨师状态检查失败:', error)
      Taro.showToast({
        title: '处理失败',
        icon: 'none'
      })
    } finally {
      setProcessing(false)
    }
  }
  
  // 手动触发生日奖励检查
  const handleCheckBirthdayRewards = async () => {
    if (!state.currentUser || !isOnline) return
    
    setProcessing(true)
    try {
      // 检查用户权限
      if (state.currentUser.role !== 'chef') {
        Taro.showToast({
          title: '权限不足',
          icon: 'none'
        })
        return
      }
      
      // 执行生日奖励检查
      const rewardedCount = await scheduledTasks.manualCheckBirthdayRewards()
      
      Taro.showToast({
        title: `已处理${rewardedCount}个生日奖励`,
        icon: 'success'
      })
    } catch (error) {
      console.error('生日奖励检查失败:', error)
      Taro.showToast({
        title: '处理失败',
        icon: 'none'
      })
    } finally {
      setProcessing(false)
    }
  }
  
  // 处理通知开关变化
  const handleNotificationChange = (e) => {
    const enabled = e.detail.value
    setNotificationEnabled(enabled)
    
    // 保存设置
    try {
      Taro.setStorageSync('notificationEnabled', enabled)
      
      Taro.showToast({
        title: enabled ? '已开启通知' : '已关闭通知',
        icon: 'success'
      })
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  }
  
  // 处理生日设置
  const handleBirthdayChange = (e) => {
    const value = e.detail.value
    setBirthday(value)
  }
  
  // 保存生日设置
  const handleSaveBirthday = async () => {
    if (!state.currentUser || !isOnline) return
    
    setSavingBirthday(true)
    try {
      // 解析生日
      const [month, day] = birthday.split('-').map(Number)
      
      // 创建生日日期（使用当前年份）
      const currentYear = new Date().getFullYear()
      const birthdayDate = new Date(currentYear, month - 1, day)
      
      // 更新用户信息
      await CloudDataManager.updateData('users', state.currentUser.id, {
        birthday: birthdayDate,
        updatedAt: new Date()
      })
      
      // 更新全局状态
      dispatch({
        type: 'SET_USER',
        payload: {
          ...state.currentUser,
          birthday: birthdayDate
        }
      })
      
      Taro.showToast({
        title: '生日设置已保存',
        icon: 'success'
      })
    } catch (error) {
      console.error('保存生日设置失败:', error)
      Taro.showToast({
        title: '保存失败',
        icon: 'none'
      })
    } finally {
      setSavingBirthday(false)
    }
  }
  
  // 清除本地缓存
  const handleClearCache = () => {
    Taro.showModal({
      title: '确认清除',
      content: '确定要清除本地缓存数据吗？这将清除所有离线数据。',
      success: (res) => {
        if (res.confirm) {
          try {
            Taro.clearStorageSync()
            
            Taro.showToast({
              title: '缓存已清除',
              icon: 'success'
            })
            
            // 重新加载页面
            setTimeout(() => {
              Taro.reLaunch({
                url: '/pages/index/index'
              })
            }, 1500)
          } catch (error) {
            console.error('清除缓存失败:', error)
            Taro.showToast({
              title: '清除失败',
              icon: 'none'
            })
          }
        }
      }
    })
  }
  
  return (
    <View className='settings-page'>
      {/* 网络状态提示 */}
      <NetworkStatus onStatusChange={handleNetworkStatusChange} />
      
      {/* 通用设置 */}
      <View className='settings-section'>
        <View className='section-title'>通用设置</View>
        
        <View className='setting-item'>
          <Text className='setting-label'>接收通知</Text>
          <Switch 
            checked={notificationEnabled}
            onChange={handleNotificationChange}
            color='#ff6b00'
          />
        </View>
        
        {state.currentUser && (
          <View className='setting-item'>
            <Text className='setting-label'>生日设置</Text>
            <View className='birthday-setting'>
              <Picker
                mode='date'
                fields='month-day'
                value={birthday}
                onChange={handleBirthdayChange}
              >
                <View className='picker-value'>
                  {birthday || '请选择生日'}
                  <Text className='picker-arrow'>▼</Text>
                </View>
              </Picker>
              <Button 
                className='setting-button'
                onClick={handleSaveBirthday}
                loading={savingBirthday}
                disabled={!birthday || savingBirthday || !isOnline}
                size='mini'
              >
                保存
              </Button>
            </View>
          </View>
        )}
        
        <View className='setting-item'>
          <Text className='setting-label'>清除本地缓存</Text>
          <Button 
            className='setting-button'
            onClick={handleClearCache}
            size='mini'
          >
            清除
          </Button>
        </View>
      </View>
      
      {/* 管理员设置 */}
      {state.currentUser && state.currentUser.role === 'chef' && (
        <View className='settings-section'>
          <View className='section-title'>管理员设置</View>
          
          <View className='setting-item'>
            <Text className='setting-label'>积分过期检查</Text>
            <Button 
              className='setting-button'
              onClick={handleCheckPointsExpiration}
              loading={processing}
              disabled={!isOnline || processing}
              size='mini'
            >
              执行
            </Button>
          </View>
          
          <View className='setting-item'>
            <Text className='setting-label'>厨师状态检查</Text>
            <Button 
              className='setting-button'
              onClick={handleCheckChefStatus}
              loading={processing}
              disabled={!isOnline || processing}
              size='mini'
            >
              执行
            </Button>
          </View>
          
          <View className='setting-item'>
            <Text className='setting-label'>生日奖励检查</Text>
            <Button 
              className='setting-button'
              onClick={handleCheckBirthdayRewards}
              loading={processing}
              disabled={!isOnline || processing}
              size='mini'
            >
              执行
            </Button>
          </View>
        </View>
      )}
      
      {/* 关于信息 */}
      <View className='settings-section'>
        <View className='section-title'>关于</View>
        
        <View className='about-info'>
          <Text className='app-name'>餐厅小程序</Text>
          <Text className='app-version'>版本 1.0.0</Text>
          <Text className='app-copyright'>© 2023 All Rights Reserved</Text>
        </View>
      </View>
      
      {/* 离线提示 */}
      {!isOnline && (
        <View className='offline-warning'>
          <Text>您当前处于离线状态，部分功能可能受限</Text>
        </View>
      )}
    </View>
  )
}

export default Settings

// 配置页面
Settings.config = {
  navigationBarTitleText: '设置'
} 